package com.yuantu.judiciary.serviceimpl;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.yuantu.judiciary.dao.IAppVersionDao;
import com.yuantu.judiciary.model.domain.AppVersionDO;
import com.yuantu.judiciary.model.vo.AppVersionVO;
import com.yuantu.judiciary.service.IAppVersionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.awt.image.BufferedImage;


/**
 * 移动端版本模块接口实现
 *
 * @author syw
 * @since 2023-06-24
 **/
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AppVersionServiceImpl implements IAppVersionService {

    private final IAppVersionDao appVersionDao;

    @Override
    public AppVersionVO getLatestDownloadLink() {
        AppVersionDO appVersion = appVersionDao.findFirstByDeletedFalseOrderByCreateTimeDesc();
        return ObjectUtils.isEmpty(appVersion) ? new AppVersionVO()
                : new AppVersionVO(appVersion.getVersionNum(), appVersion.getDownloadLink(), getQRCode(appVersion.getDownloadLink()));
    }

    public static String getQRCode(String url) {
        String base64Url = "data:image/png;base64,";
        BufferedImage bufferedImage = QrCodeUtil.generate( url, 300, 300);
        byte[] bytes = ImgUtil.toBytes(bufferedImage, "png");
        return base64Url + Base64Encoder.encode(bytes);
    }

    public static void main(String[] args) {
        System.out.println(getQRCode("https://miscrofile.oss-cn-hangzhou.aliyuncs.com/root/file/0/4174/app-release.apk"));
    }

}
